import os
from datetime import datetime

from PySide2.QtWidgets import QFileDialog, QMessageBox
from src.lib.errorno import g_errno_d
from src.lib.thread_stop import stop_thread
from src.protocols.boot_dfu import BootDfuProtocols

class AppDfu():

    m_i_upgrade_flag = 0  # 0--未升级  1--升级中
    m_b_is_LF = 1  # 0--不加\r\n  1--加\r\n

    def __init__(self, ui, port):
        self.ui = ui
        self.Port = port
        self.MainWindow = self.ui.MainWindow
        self.BootUp = BootDfuProtocols(self.ui, self.Port)

    def __controlSwitch(self, state):
        self.MainWindow.btn_switchSerial.setEnabled(state)
        self.MainWindow.le_upFilePath.setEnabled(state)
        self.MainWindow.brn_upFilePath.setEnabled(state)

    def uiReadUpFile(self):
        file_name = []
        file_path = os.path.dirname(self.MainWindow.le_upFilePath.text())
        if os.path.isdir(file_path):
            path = file_path
        else:
            path = "/"
        file_name = QFileDialog.getOpenFileName(self.ui, "选择文件", path, "Dfu File(*.dfu)")
        if len(file_name[0]) > 0:
            self.MainWindow.le_upFilePath.setText(file_name[0])

    # 投递文本到[调试接收框]
    def uiForwardReceive(self, text):
        self.Port.sendTextToReceive(self.Port.Page['DEBUG'].value, text)

    # 选择升级开关
    def uiTaskSwitch(self):
        if self.Port.getPortState():
            QMessageBox.critical(self.ui, "Port Error", "请先打开串口！")
            return
        file_path = self.MainWindow.le_upFilePath.text()
        if file_path == "":
            QMessageBox.critical(self.ui, "File Error", "请先选择文件！")
            return
        if os.path.exists(file_path) is False:
            QMessageBox.critical(self.ui, "File Error", "文件不存在！")
            return

        if self.MainWindow.brn_upStartUpgrade.text() == "开始升级":
            self.uiForwardReceive("To upgrade")
            self.MainWindow.brn_upStartUpgrade.setText("停止升级")
            self.__controlSwitch(False)
            # 记录启动时间
            self.start_time = datetime.now()

            self.BootUp.Task_Start(self.start_time, file_path, "", self.m_b_is_LF)
            self.m_i_upgrade_flag = 1  # 置标志位 开始升级
        else:
            self.portUpTaskStop("用户手动停止升级", g_errno_d['FAIL'])

    def uiTaskAbort(self):
        try:
            self.BootUp.closeUpFile()
        except Exception:
            pass
        self.MainWindow.brn_upStartUpgrade.setText("开始升级")
        self.__controlSwitch(True)

    def portUpTaskStop(self, msg, flag):
        self.uiForwardReceive(msg)

        time_s = str((datetime.now() - self.start_time).total_seconds())[:-3]
        self.uiForwardReceive("用时:" + time_s + "s")
        print("总共用时:" + time_s + "s")

        self.m_i_upgrade_flag = 0  # 置标志位 停止升级
        self.BootUp.rx_buff.queue.clear()
        self.uiTaskAbort()

        if flag == g_errno_d['OK']:
            self.Port.msg_signal.emit(0, "提示", "升级成功!")
        else:
            self.Port.msg_signal.emit(3, "提示", "升级失败!(可能版本一致)")
        '''线程终止Kill'''
        try:
            stop_thread(self.BootUp.BootUpThr)
            # stop_thread(self.BootUp.LoopThr)
        except Exception:
            pass
